﻿using AnyLink.Domain.ViewModels;
using AnyLink.Infrastructure.Utils;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Net;

namespace AnyLink.Infrastructure.Filters
{
    /// <summary>
    /// 全局异常过滤器
    /// </summary>
    public class GlobalExceptionFilter : IExceptionFilter
    {
        readonly ILogger<GlobalExceptionFilter> _logger;
        readonly IWebHostEnvironment _hostEnvironment;
        public GlobalExceptionFilter(IWebHostEnvironment hostEnvironment, ILogger<GlobalExceptionFilter> logger)
        {
            _hostEnvironment = hostEnvironment;
            _logger = logger;
        }
        public void OnException(ExceptionContext context)
        {
            if (!context.ExceptionHandled)
            {
                var result = new ResultJsonView<string>
                {
                    Code = (int)HttpStatusCode.InternalServerError,
                    Message = "服务器发生未处理的异常"
                };
                if (_hostEnvironment.IsDevelopment())
                {
                    result.Message += "：" + context.Exception.Message;
                    result.Data = context.Exception.StackTrace;
                }
                context.Result = new ContentResult
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    ContentType = "application/json;charset=utf-8",
                    Content = result.ToJson()
                };
                _logger.LogError($"服务器内部错误：{result.ToJson()}");
                context.ExceptionHandled = true;
            }
        }
    }
}
